{
 "cells": [
  {
   "cell_type": "code",
   "execution_count": 1,
   "id": "119e48b8",
   "metadata": {},
   "outputs": [],
   "source": [
    "import openai # 导入OpenAI，用于调用聊天模型\n",
    "import IPython # 导入IPython，用于展示聊天输出\n",
    "\n",
    "# 这里替换为你的 OpenAI API 密钥\n",
    "openai.api_key  = 'sk-xxxxx'"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 2,
   "id": "bed5b887",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 设置OpenAI API调用参数\n",
    "def set_open_params(\n",
    "#     model=\"text-davinci-003\", # 模型\n",
    "    model=\"gpt-3.5-turbo\", # 模型\n",
    "    temperature=0.7, # 多样性\n",
    "    n = 1, # 返回结果的数量\n",
    "    max_tokens=256, # 生成结果的最大词数\n",
    "    top_p=1, # 随机抽样的阈值\n",
    "    frequency_penalty=0, # 调整生成的文本的常见度\n",
    "    presence_penalty=0, # 调整生成的文本中的新概念出现的频率\n",
    "):\n",
    "    openai_params = {}    \n",
    "    openai_params['model'] = model  # 使用的模型名称\n",
    "    openai_params['temperature'] = temperature  # 结果多样性的参数，数值越大结果越随机，反之越确定\n",
    "    openai_params['n'] = n  # 返回结果的数量\n",
    "    openai_params['max_tokens'] = max_tokens  # 生成结果的最大词数\n",
    "    openai_params['top_p'] = top_p  # 随机抽样的阈值，较小的值将使结果更加集中，较大的值将使结果更加分散\n",
    "    openai_params['frequency_penalty'] = frequency_penalty  # 调整生成的文本的常见度，较高的值将使模型更可能生成罕见的文本\n",
    "    openai_params['presence_penalty'] = presence_penalty  # 调整生成的文本中的新概念出现的频率，较高的值将使模型更可能引入新的概念\n",
    "    return openai_params\n",
    "\n",
    "params = set_open_params() # 设置参数"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 4,
   "id": "27ca8bee",
   "metadata": {},
   "outputs": [],
   "source": [
    "# 从OpenAI API获取完成的文本\n",
    "def get_completion(params, prompt):\n",
    "    messages = [{\"role\": \"user\", \"content\": prompt}]  # 用户角色发送一个消息，消息的内容为我们的提示文本\n",
    "    response = openai.ChatCompletion.create(  # 调用ChatCompletion API\n",
    "        model = params['model'], # 模型\n",
    "        messages=messages, # Prompt消息\n",
    "        temperature = params['temperature'], # 多样性\n",
    "        n = params['n'], # 返回结果的数量\n",
    "        max_tokens = params['max_tokens'], # 生成结果的最大词数\n",
    "        top_p = params['top_p'], # 随机抽样的阈值\n",
    "        frequency_penalty = params['frequency_penalty'], # 生成的文本的常见度\n",
    "        presence_penalty = params['presence_penalty'], # 生成的文本中的新概念出现的频率\n",
    "    )\n",
    "    return response # 接收模型的聊天返回结果"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 5,
   "id": "bd6a5d16",
   "metadata": {},
   "outputs": [
    {
     "data": {
      "text/plain": [
       "<OpenAIObject chat.completion id=chatcmpl-7UY020mbDv3iBfOr0sIn6o0OzrHp3 at 0x1f4ae7b2ca0> JSON: {\n",
       "  \"choices\": [\n",
       "    {\n",
       "      \"finish_reason\": \"stop\",\n",
       "      \"index\": 0,\n",
       "      \"message\": {\n",
       "        \"content\": \"a natural satellite that orbits around the Earth. It is the fifth-largest moon in the solar system and is approximately one-quarter the size of the Earth. The moon is believed to have formed about 4.5 billion years ago, shortly after the formation of the solar system. It has no atmosphere, no water, and no life, but it is responsible for the tides on Earth and has played a significant role in human culture and mythology throughout history.\",\n",
       "        \"role\": \"assistant\"\n",
       "      }\n",
       "    }\n",
       "  ],\n",
       "  \"created\": 1687514890,\n",
       "  \"id\": \"chatcmpl-7UY020mbDv3iBfOr0sIn6o0OzrHp3\",\n",
       "  \"model\": \"gpt-3.5-turbo-0301\",\n",
       "  \"object\": \"chat.completion\",\n",
       "  \"usage\": {\n",
       "    \"completion_tokens\": 91,\n",
       "    \"prompt_tokens\": 11,\n",
       "    \"total_tokens\": 102\n",
       "  }\n",
       "}"
      ]
     },
     "execution_count": 5,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "# 简单示例\n",
    "prompt = \"The moon is\" # 设置Prompt\n",
    "response = get_completion(params, prompt) # 调用API\n",
    "response"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": 9,
   "id": "34f854e8",
   "metadata": {},
   "outputs": [
    {
     "name": "stdout",
     "output_type": "stream",
     "text": [
      "<class 'openai.openai_object.OpenAIObject'>\n",
      "{\n",
      "  \"content\": \"a natural satellite that orbits around the Earth. It is the fifth-largest moon in the solar system and is approximately one-quarter the size of the Earth. The moon is believed to have formed about 4.5 billion years ago, shortly after the formation of the solar system. It has no atmosphere, no water, and no life, but it is responsible for the tides on Earth and has played a significant role in human culture and mythology throughout history.\",\n",
      "  \"role\": \"assistant\"\n",
      "}\n"
     ]
    },
    {
     "data": {
      "text/markdown": [
       "a natural satellite that orbits around the Earth. It is the fifth-largest moon in the solar system and is approximately one-quarter the size of the Earth. The moon is believed to have formed about 4.5 billion years ago, shortly after the formation of the solar system. It has no atmosphere, no water, and no life, but it is responsible for the tides on Earth and has played a significant role in human culture and mythology throughout history."
      ],
      "text/plain": [
       "<IPython.core.display.Markdown object>"
      ]
     },
     "execution_count": 9,
     "metadata": {},
     "output_type": "execute_result"
    }
   ],
   "source": [
    "import IPython\n",
    "print(type(response))\n",
    "print(response.choices[0].message)\n",
    "IPython.display.Markdown(response.choices[0].message[\"content\"])"
   ]
  },
  {
   "cell_type": "code",
   "execution_count": null,
   "id": "a35fdceb",
   "metadata": {},
   "outputs": [],
   "source": []
  }
 ],
 "metadata": {
  "kernelspec": {
   "display_name": "Python 3 (ipykernel)",
   "language": "python",
   "name": "python3"
  },
  "language_info": {
   "codemirror_mode": {
    "name": "ipython",
    "version": 3
   },
   "file_extension": ".py",
   "mimetype": "text/x-python",
   "name": "python",
   "nbconvert_exporter": "python",
   "pygments_lexer": "ipython3",
   "version": "3.10.11"
  }
 },
 "nbformat": 4,
 "nbformat_minor": 5
}
